package controller;

import dao.ArticleDao;
import entity.Article;
import entity.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;

@WebServlet("/article/create")
public class ArticleCreateServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //显示编辑文章页面
        request.getRequestDispatcher("/editArticle.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取文章表单提交的文章明细信息
        String title = request.getParameter("title");
        String summary = request.getParameter("summary");
        String content = request.getParameter("content");


        //文章文字个数
        Integer wordTotak = content.length();
        //从session作用域获取当前的登录用户，文章作者id
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("login_user");
        Integer uid = user.getId();

        //调用dao层添加文章
        int total = ArticleDao.addArticle(uid,title,summary,content,wordTotak);

        //根据total判断，添加成功跳转main页面
        if (total>0){
            //添加成功
            response.sendRedirect("/main");
        }else {
            request.setAttribute("errorMsg","添加文章失败");
            request.getRequestDispatcher("/error.jsp").forward(request,response);
        }


    }
}
